package com.atech.ebayadmin.batchservice.action;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import com.atech.ebayadmin.common.ConstConfig;
import com.atech.ebayadmin.common.pager.Pager;
import com.atech.ebayadmin.common.pager.PagerHelper;
import com.atech.ebayadmin.common.struts.BaseAction;
import com.atech.ebayadmin.invoice.model.Invoice;
import com.atech.ebayadmin.invoice.service.IInvoiceService;
import com.atech.ebayadmin.invoice.util.FileCreate;
import com.atech.ebayadmin.invoice.vo.InvoiceVO;

public class BatchAction extends BaseAction{
	
    /**
	 * 
	 */
	private static final long serialVersionUID = 9061239445358723647L;
	private static final Log log = LogFactory.getLog(BatchAction.class);
    private IInvoiceService newInvoiceService ;

	/**
	 * @return the newInvoiceService
	 */
	public IInvoiceService getNewInvoiceService() {
		return newInvoiceService;
	}
	/**
	 * @param newInvoiceService the newInvoiceService to set
	 */
	public void setNewInvoiceService(IInvoiceService newInvoiceService) {
		this.newInvoiceService = newInvoiceService;
	}
	
	/**************************************************************/

	//action to retrieve all invoice entries
	public String importFile() throws Exception {
		
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			InvoiceVO vo = new InvoiceVO();
			vo.setTitle(getTitleStr());
			vo.setEBayAct(getEbayAct());
			vo.setItemID(getItemId());
			vo.setBegin_time(begin_time);
			vo.setEnd_time(end_time);
			
			if(vo.getEnd_time() != null ){
				vo.getEnd_time().add(Calendar.DAY_OF_MONTH, 1);
			}
			log.info("进入帐单查询接口");
			Pager pager = PagerHelper.getPager(request);
			List list = newInvoiceService.listInvoice(vo, pager);
			if(vo.getEnd_time() != null ){
				end_time.add(Calendar.DAY_OF_MONTH, -1);
			}
			this.setInvoiceEntries(list);
			this.drawChart();
			request.setAttribute("pager", pager);
	        return SUCCESS;
		}catch (Exception e) {
			ServletActionContext.getRequest().setAttribute("message", e.getMessage());
			return super.handleException(e);
		}
    }
	
	

	/******************* Section for Interface to JSP ********************/
	private String ebayAct = null;
	private Calendar begin_time = null;
	private Calendar end_time = null;
	//invoice entries to be shown
	private List invoiceEntries = null;
	//used to get filter string - Title
	private String titleStr=null;
	
	//used to get filter string - eBayAct
	private String actStr=null;
	//URL used to store the location of the JFreeChart result
	private String chartURL = "";
	
	private String itemId;
	private String startDay;
	
	private String endDay;

	/**
	 * @return the itemId
	 */
	public String getItemId() {
		return itemId;
	}
	/**
	 * @param itemId the itemId to set
	 */
	public void setItemId(String itemId) {
		this.itemId = itemId;
	}
	public void setEbayAct(String ebayAct) {
		this.ebayAct = ebayAct;
	}
	public String getEbayAct() {
		return ebayAct;
	}

	public Calendar getBegin_time() {
		return begin_time;
	}
	public void setBegin_time(Calendar begin_time) {
		this.begin_time = begin_time;
	}
	
	public Calendar getEnd_time() {
		return end_time;
	}
	public void setEnd_time(Calendar end_time) {
		this.end_time = end_time;
	}

	public List getInvoiceEntries() {
		return invoiceEntries;
	}
	public void setInvoiceEntries(List invoiceEntries) {
		this.invoiceEntries = invoiceEntries;
	}
	
	public String getTitleStr() {
		return titleStr;
	}
	
	public void setTitleStr(String titleStr) {
		this.titleStr = titleStr;
		System.out.println("setTitleStr is: "+ titleStr);
	}

	public String getActStr() {
		return actStr;
	}
	
	public void setActStr(String actStr) {
		this.actStr = actStr;
	}
	
	public String getChartURL() {
		return chartURL;
	}
	
	public void setChartURL(String chartURL) {
		this.chartURL = chartURL;
	}
	
	//To be shown in the dropdown list 
	private List actList = null;
	
	public List getActList() {
		return actList;
	}
	
	public void setActList(List actList) {
		this.actList = actList;
	}
	
	//To be shown in the dropdown list 
	private List titleList = null;
	
	public List getTitleList() {
		return titleList;
	}
	
	public void setTitleList(List titleList) {
		this.titleList = titleList;
	}
	
	//action to retrieve all invoice entries
	public String listInvoice() throws Exception {
		
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			InvoiceVO vo = new InvoiceVO();
			vo.setTitle(getTitleStr());
			vo.setEBayAct(getEbayAct());
			vo.setItemID(getItemId());
			vo.setBegin_time(begin_time);
			vo.setEnd_time(end_time);
			if(vo.getEnd_time() != null ){
				vo.getEnd_time().add(Calendar.DAY_OF_MONTH, 1);
			}
			log.info("进入帐单查询接口");
			Pager pager = PagerHelper.getPager(request);
			List list = newInvoiceService.listInvoice(vo, pager);
			if(vo.getEnd_time() != null ){
				end_time.add(Calendar.DAY_OF_MONTH, -1);
			}
			this.setInvoiceEntries(list);
			this.drawChart();
			request.setAttribute("pager", pager);
	        return SUCCESS;
		}catch (Exception e) {
			ServletActionContext.getRequest().setAttribute("message", e.getMessage());
			return super.handleException(e);
		}
    }
	public void exportOrder() throws Exception {
		OutputStream output = null;
		FileInputStream fis = null;
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpServletResponse response = ServletActionContext.getResponse();
			InvoiceVO vo = new InvoiceVO();
			vo.setTitle(getTitleStr());
			vo.setEBayAct(getEbayAct());
			vo.setItemID(getItemId());
			vo.setBegin_time(begin_time);
			vo.setEnd_time(end_time);
			vo.setBegin_time(begin_time);
			vo.setEnd_time(end_time);//Calendar.getInstance().setTime(date)
			if(vo.getEnd_time() != null ){
				vo.getEnd_time().add(Calendar.DAY_OF_MONTH, 1);
			}
			List<Invoice> reportList = newInvoiceService.listInvoice(vo);
			if(vo.getEnd_time() != null ){
				end_time.add(Calendar.DAY_OF_MONTH, -1);
			}
			String fileSaveaddr = FileCreate.createOrderDetail(reportList, "");
			response.reset();
			byte[] fileNameByte = ("invoiceReport" + ".xls").getBytes("GBK");
			String fileName = new String(fileNameByte, "8859_1");
			response.addHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			output = response.getOutputStream();
			fis = new FileInputStream(fileSaveaddr);
			byte[] b = new byte[1024];
			int i = 0;
			while ((i = fis.read(b)) > 0) {
				output.write(b, 0, i);
			}
			output.flush();
		}catch (Exception e) {
			e.printStackTrace();
		}finally{		
			fis.close();
			output.close();
		}

    }
	
	public String drawChart() throws Exception {
		
		JFreeChart chart = null;
		
		TimeSeries TS0 = new TimeSeries("Data");
		
		for (int i=0; i < invoiceEntries.size(); i++)
		{
			Invoice iTmp = (Invoice)invoiceEntries.get(i);
			int year = iTmp.getDate().get(Calendar.YEAR);
			//System.out.println("Year is:"+year);
			int month = iTmp.getDate().get(Calendar.MONTH) + 1;
			//System.out.println("Month is:"+month);
			int day = iTmp.getDate().get(Calendar.DAY_OF_MONTH);
			//System.out.println("Day is:"+day);
			TS0.addOrUpdate(new Day(day,month,year),iTmp.getBalance().getValue());
		}
		
		TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();
        timeseriescollection.addSeries(TS0);
        
        chart = ChartFactory.createTimeSeriesChart(
                "Chart",
                "X/Time", 
                "Y/Value", 
                timeseriescollection,
                true,
                true,
                false
            );
		
		if (chart == null)
		{
			System.out.println("null chart!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		}
		
		FileOutputStream fos_jpg = null;
		try {
			 String name = String.valueOf(System.currentTimeMillis());
			 String fileName = name+".jpg";
		//	 this.setChartURL("pages\\images\\"+fileName);
			 this.setChartURL(name);
		     fos_jpg=new FileOutputStream(ConstConfig.contextPath+"\\pages\\images\\"+fileName);
		     //ChartUtilities.writeChartAsJPEG(fos_jpg,100,chart,640,480,null);
			 ChartUtilities.writeChartAsPNG(fos_jpg,chart,640,480,null);
		     fos_jpg.close();  
		} catch (Exception e) {
		}  
		
		return "";
	}
	/**
	 * @return the startDay
	 */
	public String getStartDay() {
		return startDay;
	}
	/**
	 * @param startDay the startDay to set
	 */
	public void setStartDay(String startDay) {
		this.startDay = startDay;
	}
	/**
	 * @return the endDay
	 */
	public String getEndDay() {
		return endDay;
	}
	/**
	 * @param endDay the endDay to set
	 */
	public void setEndDay(String endDay) {
		this.endDay = endDay;
	}
	

			
}
